/**
 * WeChat Mini Program API Polyfill
 * 解决WeChat API兼容性问题
 */

// 检查是否在微信小程序环境中
const isWeixinMiniProgram = () => {
  // #ifdef MP-WEIXIN
  return true;
  // #endif
  
  // #ifndef MP-WEIXIN
  return false;
  // #endif
};

// 创建安全的wx对象
const createSafeWx = () => {
  if (typeof wx !== 'undefined') {
    return wx;
  }
  
  // 创建一个模拟的wx对象，包含常用的空方法
  return {
    // 分享相关API的空实现
    shareVideoMessage: () => {
      console.warn('shareVideoMessage is not supported in current environment');
    },
    shareAppMessage: () => {
      console.warn('shareAppMessage is not supported in current environment');
    },
    shareToTimeline: () => {
      console.warn('shareToTimeline is not supported in current environment');
    },
    
    // 其他常用API的空实现
    getMenuButtonBoundingClientRect: () => {
      return {
        width: 87,
        height: 32,
        top: 48,
        right: 365,
        bottom: 80,
        left: 278
      };
    },
    
    getSystemInfo: (options) => {
      if (options && options.fail) {
        options.fail({ errMsg: 'getSystemInfo:fail not supported' });
      }
    },
    
    // 通用的空方法
    request: () => {},
    uploadFile: () => {},
    downloadFile: () => {},
    showToast: () => {},
    showModal: () => {},
    navigateTo: () => {},
    redirectTo: () => {},
    switchTab: () => {},
    navigateBack: () => {}
  };
};

// 初始化安全的wx对象
if (!isWeixinMiniProgram() && typeof wx === 'undefined') {
  global.wx = createSafeWx();
}

// 为现有的wx对象添加缺失的方法
if (typeof wx !== 'undefined' && !wx.shareVideoMessage) {
  wx.shareVideoMessage = () => {
    console.warn('shareVideoMessage is not supported in current WeChat version');
  };
}

export default {
  isWeixinMiniProgram,
  createSafeWx
};
